package com.winsdom.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.winsdom.entity.CustomerBillingConfig;
import com.winsdom.mapper.CustomerBillingConfigMapper;
import com.winsdom.service.ICustomerBillingConfigService;
import com.winsdom.vo.CustomerBillingConfigQueryVO;
import com.winsdom.vo.CustomerBillingConfigUpdateVO;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

/**
 * <p>
 * 客户票据配置表 服务实现类
 * </p>
 *
 * @author 
 * @since 2025-05-12
 */
@Slf4j
@Service
public class CustomerBillingConfigServiceImpl extends ServiceImpl<CustomerBillingConfigMapper, CustomerBillingConfig> implements ICustomerBillingConfigService {

    @Override
    public CustomerBillingConfigQueryVO getBillingConfigByCustomerId(Long customerId) {
        Assert.notNull(customerId, "客户ID不能为空");
        return baseMapper.selectBillingConfigByCustomerId(customerId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateBillingConfig(CustomerBillingConfigUpdateVO updateVO) {
        log.info("开始更新客户开票配置，更新信息：{}", updateVO);
        
        // 参数校验
        Assert.notNull(updateVO, "更新信息不能为空");
        Assert.notNull(updateVO.getCustomerId(), "客户ID不能为空");

        // 查询现有配置
        LambdaQueryWrapper<CustomerBillingConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CustomerBillingConfig::getCustomerId, updateVO.getCustomerId());
        CustomerBillingConfig existingConfig = getOne(wrapper);
        
        // 校验配置是否存在
        Assert.notNull(existingConfig, "客户开票配置不存在");
        log.info("找到现有配置：{}", existingConfig);

        // 只更新非空字段
        if (updateVO.getBillingType() != null) {
            existingConfig.setBillingType(updateVO.getBillingType());
        }
        if (updateVO.getAutoBillingEnabled() != -1) {
            existingConfig.setAutoBillingEnabled(updateVO.getAutoBillingEnabled());
        }
        if (updateVO.getBillingMethod() != null) {
            existingConfig.setBillingMethod(updateVO.getBillingMethod());
        }
        if (updateVO.getBillingRule() != null) {
            existingConfig.setBillingRule(updateVO.getBillingRule());
        }
        if (updateVO.getCustomRemarkEnabled() != -1) {
            existingConfig.setCustomRemarkEnabled(updateVO.getCustomRemarkEnabled());
        }

        // 更新配置
        boolean success = updateById(existingConfig);
        log.info("更新客户开票配置{}，更新后的配置：{}", success ? "成功" : "失败", existingConfig);
    }
}
